package com.heima.commnet.service.impl;

import com.heima.commnet.feign.UserFeign;
import com.heima.commnet.service.CommentService;
import com.heima.common.aliyun.GreeTextScan;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApUserThreadLocal;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private GreeTextScan greeTextScan;

    /**
     * 保存评论
     *
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {

        //查询参数
        if (null == dto) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getContent() != null && dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "评论内容不能超过140字");
        }

        //查询是否登录
        ApUser user = ApUserThreadLocal.getUser();
        if (null == user) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //文字安全校验
        try {
            Map textScan = greeTextScan.greeTextScan(dto.getContent());
            //判断是否违规
            if (!textScan.get("suggestion").equals("pass")) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能超过140字");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //获取当前详细信息
        ApUser apUser = userFeign.findUserById(Long.valueOf(user.getId()));
        if (null == apUser) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //保存数据
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setEntryId(dto.getArticleId());
        apComment.setType((short) 0);
        apComment.setContent(dto.getContent());
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short) 0);
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());

        mongoTemplate.save(apComment);

        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {

        //查询参数
        if (null == dto) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getCommentId() != null && (dto.getOperation() != 0 && dto.getOperation() != 1)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //查询是否登录
        ApUser user = ApUserThreadLocal.getUser();
        if (null == user) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //查询是否点赞过
        ApCommentLike commentLike = this.mongoTemplate.findOne(
                Query.query(Criteria.where("commentId").is(dto.getCommentId())
                        .and("authorId").is(user.getId())), ApCommentLike.class);
        if (null == commentLike) {
            //为查询到 保存数据
            commentLike = new ApCommentLike();
            commentLike.setAuthorId(user.getId());
            commentLike.setCommentId(dto.getCommentId());
            commentLike.setOperation(dto.getOperation());

            //保存
            mongoTemplate.save(commentLike);

        } else {
            //查询到 更新数据
            commentLike.setOperation(dto.getOperation());

            mongoTemplate.save(commentLike);
        }

        //更改评论数量
        ApComment apComment = this.mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (null == apComment) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (dto.getOperation() == 0) {
            //点赞 增加点赞数
            apComment.setLikes(apComment.getLikes() + 1);

            this.mongoTemplate.save(apComment);
        } else {
            //取消点赞 较少点赞数
            apComment.setLikes(apComment.getLikes() - 1);

            this.mongoTemplate.save(apComment);
        }

        //5.数据返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes",apComment.getLikes());
        return ResponseResult.okResult(resultMap);
    }

    /**
     * 查询评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDto dto) {

        //查询参数
        if (null == dto) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getSize() == null || dto.getSize() == 0){
            dto.setSize(20);
        }

        //查询评论
        List<ApComment> apCommentList = this.mongoTemplate.find(
                Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("likes").lte(dto.getMinLikes()))
                        .with(Sort.by(Sort.Order.desc("likes"),Sort.Order.desc("createdTime"))).limit(dto.getSize()),
                ApComment.class);
        if (null == apCommentList && apCommentList.size() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
        }

        //查询是否登录
        ApUser user = ApUserThreadLocal.getUser();
        if (null == user) {

            //为登录 直接返回
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        } else if (user.getId() == 0) {

            //游客登录 返回数据
            return ResponseResult.okResult(apCommentList);
        }

        //非游客登录 查询当前用户的评论点赞记录
        //获取当前所有评论id
        List<String> idList = apCommentList.stream().map(x -> x.getId()).collect(Collectors.toList());

        //查询数据
        List<ApCommentLike> apCommentLikes = this.mongoTemplate.find(Query.query(Criteria.where("authorId")
                .is(user.getId()).and("commentId").in(idList).and("operation").is(0)), ApCommentLike.class);

        //封装数据
        List<ApCommentVo> resultList = new ArrayList<>();
        if(apCommentLikes != null){
            apCommentList.stream().forEach(x->{
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(x,apCommentVo);
                for (ApCommentLike apCommentLike : apCommentLikes) {
                    if(x.getId().equals(apCommentLike.getCommentId())){
                        apCommentVo.setOperation((short)0);
                        break;
                    }
                }
                resultList.add(apCommentVo);
            });
        }

        return ResponseResult.okResult(resultList);
    }

}
